﻿using System;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace wojilu
{
    /// <summary>
    /// 字符文字处理类
    /// </summary>
    public static class StringHelper
    {
        private static Regex RegexBr = new Regex(@"(\r\n)", RegexOptions.IgnoreCase);
        private static readonly Regex REGEX_LINE_BREAKS = new Regex(@"\n\s*", RegexOptions.Compiled);
        private static readonly Regex REGEX_LINE_SPACE = new Regex(@"\n\s*\r", RegexOptions.Compiled);
        private static readonly Regex REGEX_SPACE = new Regex(@"( )+", RegexOptions.Compiled);
        private static readonly Regex REGEX_BR = new Regex(@"(\r\n)", RegexOptions.IgnoreCase | RegexOptions.Multiline);

        #region 截取字符串

        #region 超出的字以...显示
        /// <summary>
        /// 超出的字以...显示
        /// </summary>
        /// <param name="str">字符窜</param>
        /// <param name="n">要显示的字数</param>
        /// <returns></returns>
        public static string stringformat(this string str, int n)
        {
            //格式化字符串长度，超出部分显示省略号,区分汉字跟字母。汉字2个字节，字母数字一个字节
            string temp = string.Empty;
            if (System.Text.Encoding.Default.GetByteCount(str) <= n)//如果长度比需要的长度n小,返回原字符串
            {
                return str;
            }
            else
            {
                int t = 0;
                char[] q = str.ToCharArray();
                for (int i = 0; i < q.Length && t < n; i++)
                {
                    if ((int)q[i] >= 0x4E00 && (int)q[i] <= 0x9FA5)//是否汉字
                    {
                        temp += q[i];
                        t += 2;
                    }
                    else
                    {
                        temp += q[i];
                        t++;
                    }
                }
                return (temp + "...");
            }
        }

        #region 字符串如果操过指定长度则将超出的部分用指定字符串代替
        /// <summary>
        /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
        /// </summary>
        /// <param name="p_SrcString">要检查的字符串</param>
        /// <param name="p_Length">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetSubString(this string p_SrcString, int p_Length, string p_TailString)
        {
            return GetSubString(p_SrcString, 0, p_Length, p_TailString);
        }
        #endregion

        #region 取指定长度的字符串
        /// <summary>
        /// 取指定长度的字符串
        /// </summary>
        /// <param name="str">要检查的字符串</param>
        /// <param name="len">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetUnicodeSubString(this string str, int len, string p_TailString)
        {
            string result = string.Empty;// 最终返回的结果
            int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
            int charLen = str.Length;// 把字符平等对待时的字符串长度
            int byteCount = 0;// 记录读取进度
            int pos = 0;// 记录截取位置
            if (byteLen > len)
            {
                for (int i = 0; i < charLen; i++)
                {
                    if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                        byteCount += 2;
                    else// 按英文字符计算加1
                        byteCount += 1;
                    if (byteCount > len)// 超出时只记下上一个有效位置
                    {
                        pos = i;
                        break;
                    }
                    else if (byteCount == len)// 记下当前位置
                    {
                        pos = i + 1;
                        break;
                    }
                }

                if (pos >= 0)
                    result = str.Substring(0, pos) + p_TailString;
            }
            else
                result = str;

            return result;
        }

        /// <summary>
        /// 取指定长度的字符串
        /// </summary>
        /// <param name="p_SrcString">要检查的字符串</param>
        /// <param name="p_StartIndex">起始位置</param>
        /// <param name="p_Length">指定长度</param>
        /// <param name="p_TailString">用于替换的字符串</param>
        /// <returns>截取后的字符串</returns>
        public static string GetSubString(this string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
        {
            string myResult = p_SrcString;

            Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
            foreach (char c in Encoding.UTF8.GetChars(bComments))
            {    //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
                if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3'))
                {
                    //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
                    //当截取的起始位置超出字段串长度时
                    if (p_StartIndex >= p_SrcString.Length)
                        return "";
                    else
                        return p_SrcString.Substring(p_StartIndex,
                                                       ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
                }
            }

            if (p_Length >= 0)
            {
                byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);

                //当字符串长度大于起始位置
                if (bsSrcString.Length > p_StartIndex)
                {
                    int p_EndIndex = bsSrcString.Length;

                    //当要截取的长度在字符串的有效长度范围内
                    if (bsSrcString.Length > (p_StartIndex + p_Length))
                    {
                        p_EndIndex = p_Length + p_StartIndex;
                    }
                    else
                    {   //当不在有效范围内时,只取到字符串的结尾

                        p_Length = bsSrcString.Length - p_StartIndex;
                        p_TailString = "";
                    }

                    int nRealLength = p_Length;
                    int[] anResultFlag = new int[p_Length];
                    byte[] bsResult = null;

                    int nFlag = 0;
                    for (int i = p_StartIndex; i < p_EndIndex; i++)
                    {
                        if (bsSrcString[i] > 127)
                        {
                            nFlag++;
                            if (nFlag == 3)
                                nFlag = 1;
                        }
                        else
                            nFlag = 0;

                        anResultFlag[i] = nFlag;
                    }

                    if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
                        nRealLength = p_Length + 1;

                    bsResult = new byte[nRealLength];

                    Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);

                    myResult = Encoding.Default.GetString(bsResult);
                    myResult = myResult + p_TailString;
                }
            }

            return myResult;
        }
        #endregion

        #region 截取指定长度字符串,汉字为2个字符
        /// <summary>
        /// 截取指定长度字符串,汉字为2个字符
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string CutStrings(this string inputString, int len)
        {
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                    tempLen += 2;
                else
                    tempLen += 1;
                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }
                if (tempLen > len)
                    break;
            }
            return tempString;
        }
        #endregion

        #endregion

        #region 从字符串的指定位置开始截取到字符串结尾的子符串
        /// <summary>
        /// 从字符串的指定位置开始截取到字符串结尾的子符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <returns>子字符串</returns>
        public static string CutString(this string str, int startIndex)
        {
            return CutString(str, startIndex, str.Length);
        }
        #endregion

        #region 从字符串的指定位置截取指定长度的子字符串
        /// <summary>
        /// 从字符串的指定位置截取指定长度的子字符串
        /// </summary>
        /// <param name="str">原字符串</param>
        /// <param name="startIndex">子字符串的起始位置</param>
        /// <param name="length">子字符串的长度</param>
        /// <returns>子字符串</returns>
        public static string CutString(this string str, int startIndex, int length)
        {
            if (startIndex >= 0)
            {
                if (length < 0)
                {
                    length = length * -1;
                    if (startIndex - length < 0)
                    {
                        length = startIndex;
                        startIndex = 0;
                    }
                    else
                        startIndex = startIndex - length;
                }

                if (startIndex > str.Length)
                    return "";
            }
            else
            {
                if (length < 0)
                    return "";
                else
                {
                    if (length + startIndex > 0)
                    {
                        length = length + startIndex;
                        startIndex = 0;
                    }
                    else
                        return "";
                }
            }

            if (str.Length - startIndex < length)
                length = str.Length - startIndex;

            return str.Substring(startIndex, length);
        }
        #endregion

        #region 截取指定长度的字符串
        /// <summary>
        /// 截取指定长度的字符串
        /// </summary>
        /// <param name="String">字符串</param>
        /// <param name="Length">长度</param>
        /// <returns>截取后的字符串</returns>
        public static string SubString(this string String, int Length)
        {
            int num = 0;
            int length = 0;
            byte[] bytes = Encoding.Default.GetBytes(String);
            for (int i = 0; i < Length; i++)
            {
                if (bytes[i] > 0x7f)
                {
                    num++;
                }
                length++;
            }
            if (Math.IEEERemainder((double)num, 2.0) != 0.0)
            {
                length--;
            }
            byte[] destinationArray = new byte[length];
            Array.Copy(bytes, destinationArray, length);
            return Encoding.Default.GetString(destinationArray);
        }

        /// <summary>
        /// 获取字符串数组中的指定字符串
        /// </summary>
        /// <param name="StringArray">字符串数组</param>
        /// <param name="Index">索引</param>
        /// <returns>字符串</returns>
        public static string SubString(this string[] StringArray, int Index)
        {
            if (StringArray.Length > Index)
            {
                if (PageValidator.IsNull(StringArray[Index]))
                {
                    return string.Empty;
                }
                return StringArray[Index];
            }
            return string.Empty;
        }

        /// <summary>
        /// 截取指定长度的字符串
        /// </summary>
        /// <param name="demand"></param>
        /// <param name="length"></param>
        /// <param name="substitute"></param>
        /// <returns></returns>
        public static string SubString(this string demand, int length, string substitute)
        {
            demand = DataSecurity.HtmlDecode(demand);
            if (Encoding.Default.GetBytes(demand).Length <= length)
            {
                return demand;
            }
            ASCIIEncoding encoding = new ASCIIEncoding();
            length -= Encoding.Default.GetBytes(substitute).Length;
            int num = 0;
            StringBuilder builder = new StringBuilder();
            byte[] bytes = encoding.GetBytes(demand);
            for (int i = 0; i < bytes.Length; i++)
            {
                if (bytes[i] == 63)
                {
                    num += 2;
                }
                else
                {
                    num++;
                }
                if (num > length)
                {
                    break;
                }
                builder.Append(demand.Substring(i, 1));
            }
            builder.Append(substitute);
            return builder.ToString();
        }
        #endregion

        #region 按照字符串的实际长度截取指定长度的字符串
        /// <summary>
        /// 按照字符串的实际长度截取指定长度的字符串
        /// </summary>
        /// <param name="text">字符串</param>
        /// <param name="length">指定长度</param>
        /// <param name="cutText">附加的字符，如...</param>
        /// <returns></returns>
        public static string CutLen(this string text, int length, string cutText)
        {
            if (text == null)
            {
                return string.Empty;
            }
            int num = 0;
            int num2 = 0;
            foreach (char ch in text)
            {
                if (ch > '\x007f')
                {
                    num += 2;
                }
                else
                {
                    num++;
                }
                if (num > length)
                {
                    text = text.Substring(0, num2);
                    text = text + cutText;
                    return text;
                }
                num2++;
            }
            return text;
        }

        #endregion

        #endregion

        #region 截取字符串

        public static string CutStrByte(string str, int len)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();
            int num = 0;
            string str2 = string.Empty;
            byte[] bytes = encoding.GetBytes(str);
            for (int i = 0; i < bytes.Length; i++)
            {
                if (bytes[i] == 0x3f)
                {
                    num += 2;
                }
                else
                {
                    num++;
                }
                try
                {
                    str2 = str2 + str.Substring(i, 1);
                }
                catch
                {
                    return str2;
                }
                if (num >= len)
                {
                    return str2;
                }
            }
            return str2;
        }

        public static string SubStrByByte(string str, int n)
        {
            string str2 = string.Empty;
            if (Encoding.Default.GetByteCount(str) <= n)
            {
                return str;
            }
            int num = 0;
            char[] chArray = str.ToCharArray();
            for (int i = 0; (i < chArray.Length) && (num < n); i++)
            {
                if ((chArray[i] >= '一') && (chArray[i] <= 0x9fa5))
                {
                    str2 = str2 + chArray[i];
                    num += 2;
                }
                else
                {
                    str2 = str2 + chArray[i];
                    num++;
                }
            }
            return str2;
        }

        /// <summary>
        /// 截取文本的长度，过长则用“...”替换symbol之前的部分文本
        /// </summary>
        /// <param name="length">要调整到的长度</param>
        /// <param name="symbol">确保不被替换的文本的起始字符串，如“(”“[”等</param>
        /// <param name="content">要处理的内容</param>
        /// <returns>要处理的内容</returns>
        public static string FixLength(int length, string symbol, string content)
        {
            content = content.Trim();
            if (content.Length <= length)
                return content;
            else
            {
                int pos = content.LastIndexOf(symbol);
                int distance = content.Length - pos;
                if (length < distance + 3)
                    content = content.Substring(0, length - 2) + "...";
                else
                    content = content.Substring(0, length - distance - 2) + "..." + content.Substring(pos);
                return content;
            }
        }


        /// <summary>
        /// 按字节，取左边的Ｎ位
        /// </summary>
        /// <param name="content">要处理的内容</param>
        /// <param name="fixLength">截取的位数</param>
        /// <returns>要处理的内容</returns>
        public static string LeftB(string content, int fixLength)
        {
            if (fixLength > content.Length * 2)
                return content;

            int length = 0;
            char[] chars = content.ToCharArray();
            int i = 0;
            for (; i < chars.Length; i++)
            {
                if ((int)chars[i] < 256)
                    length++;
                else
                    length = length + 2;
                if (length > fixLength)
                    break;
            }
            if (length <= fixLength)
                return content;

            return content.Substring(0, i - 3);
        }

        /// <summary>
        /// 按字节，截取文本的长度，过长则用“...”结束
        /// </summary>
        /// <param name="fixLength">截取的位数</param>
        /// <param name="content">要处理的内容</param>
        /// <returns>要处理的内容</returns>
        public static string FixLengthB(int fixLength, string content)
        {
            if (fixLength >= content.Length * 2)
                return content;

            if (fixLength < 3)
                return LeftB(content, fixLength);

            int length = 0;
            char[] chars = content.ToCharArray();
            int i = 0;
            for (; i < chars.Length; i++)
            {
                if ((int)chars[i] < 256)
                    length++;
                else
                    length = length + 2;
                if (length > fixLength)
                    break;
            }
            if (length <= fixLength)
                return content;

            for (; i >= 0; i--)
            {
                if ((int)chars[i] < 256)
                    length--;
                else
                    length = length - 2;
                if (length <= fixLength - 3)
                    break;
            }
            return content.Substring(0, i) + "...";
        }

        /// <summary>
        /// 按字节，截取文本的长度
        /// </summary>
        /// <param name="fixLength">截取的位数</param>
        /// <param name="content">要处理的内容</param>
        /// <param name="Ellipsis">要不要省略号 1为要，0为不要</param>
        /// <returns>要处理的内容</returns>
        public static string FixLengthB(string content, int fixLength, int Ellipsis)
        {
            if (fixLength >= content.Length * 2)
                return content;

            if (fixLength < 3)
                return LeftB(content, fixLength);

            if (content == null | string.IsNullOrEmpty(content)) return "";
            content = DataSecurity.HtmlDecode(content);
            content = DataSecurity.LeachHTML(content);

            int length = 0;
            char[] chars = content.ToCharArray();
            int i = 0;
            for (; i < chars.Length; i++)
            {
                if ((int)chars[i] < 256)
                    length++;
                else
                    length = length + 2;
                if (length > fixLength)
                    break;
            }
            if (length <= fixLength)
                return content;

            for (; i >= 0; i--)
            {
                if ((int)chars[i] < 256)
                    length--;
                else
                    length = length - 2;
                if (length <= fixLength - 3)
                    break;
            }
            if (Ellipsis > 0)
            {
                content = content.Substring(0, i) + "...";
            }
            else
            {
                content = content.Substring(0, i);
            }
            content = DataSecurity.HtmlEncode(content); ;
            return content;
        }

        /// <summary>
        /// 按字节，截取文本的长度
        /// </summary>
        /// <param name="fixLength">截取的位数</param>
        /// <param name="content">要处理的内容</param>
        /// <param name="symbol">要加的符号</param>
        /// <returns>要处理的内容</returns>
        public static string FixLengthB(string content, int fixLength, string symbol)
        {
            if (fixLength >= content.Length * 2)
                return content;

            if (fixLength < 3)
                return LeftB(content, fixLength);

            if (content == null | string.IsNullOrEmpty(content)) return "";
            content = DataSecurity.HtmlDecode(content);
            content = DataSecurity.LeachHTML(content);

            int length = 0;
            char[] chars = content.ToCharArray();
            int i = 0;
            for (; i < chars.Length; i++)
            {
                if ((int)chars[i] < 256)
                    length++;
                else
                    length = length + 2;
                if (length > fixLength)
                    break;
            }
            if (length <= fixLength)
                return content;

            for (; i >= 0; i--)
            {
                if ((int)chars[i] < 256)
                    length--;
                else
                    length = length - 2;
                if (length <= fixLength - 3)
                    break;
            }
            content = content.Substring(0, i) + symbol;
            content = DataSecurity.HtmlEncode(content); ;
            return content;
        }

        /// <summary>
        /// 截取文本的长度，过长则用“...”替换symbol之前的部分文本
        /// </summary>
        /// <param name="length">要截取到的长度</param>
        /// <param name="symbol">确保不被替换的文本的起始字符串，如“(”“[”等</param>
        /// <param name="content">要处理的内容</param>
        /// <returns>要处理的内容</returns>
        public static string FixLengthB(int length, string symbol, string content)
        {
            if (length >= content.Length * 2)
                return content;

            int pos = content.LastIndexOf(symbol);
            string leftPart = content.Substring(0, pos);
            string rightPart = content.Substring(pos);
            int leftLength = LengthB(leftPart);
            int rightLength = LengthB(rightPart);

            if (length >= leftLength + rightLength)
                return content;

            if (length > rightLength + 3)
                return FixLengthB(length - rightLength, leftPart) + rightPart;

            if (length == leftLength + 3)
                return content + "...";

            if (length < leftLength + 3)
                return FixLengthB(length, leftPart);

            return leftPart + FixLengthB(length - leftLength, content);
        }

        public static int LengthB(string content)
        {
            int length = 0;
            char[] chars = content.ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                if ((int)chars[i] < 256)
                    length++;
                else
                    length = length + 2;
            }
            return length;
        }

        /// <summary>
        /// 检查字符串最大长度，返回指定长度的字符串
        /// </summary>
        /// <param name="sqlInput">输入字符串</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>			
        public static string SqlText(string sqlInput, int maxLength)
        {
            if (sqlInput != null && sqlInput != string.Empty)
            {
                sqlInput = sqlInput.Trim();
                if (sqlInput.Length > maxLength)//按最大长度截取字符串
                    sqlInput = sqlInput.Substring(0, maxLength);
            }
            return sqlInput;
        }

        /// <summary>
        /// 截取指定长度字符串,汉字为2个字符
        /// </summary>
        /// <param name="inputString"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        public static string CutTitle(string inputString, int len)
        {
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                    tempLen += 2;
                else
                    tempLen += 1;
                try
                {
                    tempString += inputString.Substring(i, 1);
                }
                catch
                {
                    break;
                }
                if (tempLen > len)
                    break;
            }
            return tempString;
        }

        #endregion


        #region 纯文本与 HTML 互换 内容
        /// <summary>
        /// 转换纯文本内容为 HTML 内容 
        /// </summary>
        /// <param name="Text">纯文本内容</param>
        /// <returns>转换后的 HTML 内容</returns>
        public static string ToHTML(this string Text)
        {
            return Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace("<p>" + Text + "</p>", "\r\n", "</p><p>"), "\r", "</p><p>"), "\n", "<br />"), "\t", "&nbsp; &nbsp; "), "  ", "&nbsp; ");
        }

        public static string HTMLToText(this string Text)
        {
            if (PageValidator.IsNull(Text)) return string.Empty;
            return Regex.Replace(Text, "<br/>", "\n");
        }

        public static string TextToHTML(this string Text)
        {
            if (PageValidator.IsNull(Text)) return string.Empty;
            return Regex.Replace(Text, "\n", "<br/>");
        }

        /// <summary>
        /// 转换 Html 内容为纯文本内容
        /// </summary>
        /// <param name="HTML">内容</param>
        /// <returns>转换后的纯文本内容</returns>
        public static string ToText(this string HTML)
        {
            string input = HTML;
            return Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(Regex.Replace(input, @"(?m)<script[^>]*>(\w|\W)*?</script[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(?m)<style[^>]*>(\w|\W)*?</style[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(?m)<select[^>]*>(\w|\W)*?</select[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(?m)<a[^>]*>(\w|\W)*?</a[^>]*>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), "(<[^>]+?>)|&nbsp;", "", RegexOptions.Multiline | RegexOptions.IgnoreCase), @"(\s)+", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        }

        #endregion

        #region Trim移除所有前导空白和后导空白字符串
        /// <summary>
        /// Trim移除所有前导空白和后导空白字符串
        /// </summary>
        /// <param name="returnStr"></param>
        /// <returns></returns>
        public static string Trim(string returnStr)
        {
            if (!string.IsNullOrEmpty(returnStr))
            {
                return returnStr.Trim();
            }
            return string.Empty;
        }

        #endregion

        #region 取左、中、右
        /// <summary>
        /// 取左边的字符
        /// </summary>
        /// <param name="sSource">字符串</param>
        /// <param name="iLength">要取长度</param>
        /// <returns></returns>
        public static string Left(this string sSource, int iLength)
        {
            if (!PageValidator.StrIsNullOrEmpty(sSource))
            {
                if (iLength > sSource.Length)
                {
                    return sSource;
                }
                else
                {
                    return sSource.Substring(0, iLength);
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 取右边的字符
        /// </summary>
        /// <param name="sSource">字符串</param>
        /// <param name="iLength">要取长度</param>
        /// <returns></returns>
        public static string Right(this string sSource, int iLength)
        {
            if (!PageValidator.StrIsNullOrEmpty(sSource))
            {
                if (iLength > sSource.Length)
                {
                    return sSource;
                }
                else
                {
                    return sSource.Substring(sSource.Length - iLength, iLength);
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 取中间的字符。
        /// </summary>
        /// <param name="sSource">字符串</param>
        /// <param name="iStart">开始长度</param>
        /// <param name="iLength">结束长度</param>
        /// <returns></returns>
        public static string Mid(this string sSource, int iStart, int iLength)
        {
            if (!PageValidator.StrIsNullOrEmpty(sSource))
            {
                int iStartPoint = iStart > sSource.Length ? sSource.Length : iStart;
                return sSource.Substring(iStartPoint, iStartPoint + iLength > sSource.Length ? sSource.Length - iStartPoint : iLength);
            }
            return string.Empty;
        }

        #endregion

        #region 去除最前和最后的p
        /// <summary>
        /// 去除最前和最后的p
        /// </summary>
        /// <param name="Strings"></param>
        /// <returns></returns>
        public static string DelHtml(string Strings)
        {
            Strings = DelFirst(Strings, "<p>");
            Strings = DelLast(Strings, "</p>");
            return Strings;
        }
        #endregion

        #region 检测某一字符串的第一个字符是否与指定的 字符一致，相同则去掉这个字符
        /// <summary>
        /// 检测某一字符串的第一个字符是否与指定的 字符一致，相同则去掉这个字符
        /// </summary>
        /// <param name="Strings">字符串</param>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string DelFirst(string Strings, string Str)
        {
            if (Strings.StrIsNullOrEmpty()) return string.Empty;
            if (Strings.Length == 0)
            {
                throw new Exception("原始字符串长度为零");
            }
            if (Strings.StartsWith(Str))
            {
                return Strings.Substring(Str.Length, Strings.Length - Str.Length);
            }
            return Strings;
        }
        #endregion

        #region 检测某一字符串的最后一个字符是否与指定的 字符一致，相同则去掉这个字符
        /// <summary>
        /// 检测某一字符串的最后一个字符是否与指定的 字符一致，相同则去掉这个字符
        /// </summary>
        /// <param name="Strings">字符串</param>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string DelLast(string Strings, string Str)
        {
            if (Strings.StrIsNullOrEmpty()) return string.Empty;
            if (Strings.Length == 0)
            {
                throw new Exception("原始字符串长度为零");
            }
            if (Strings.EndsWith(Str))
            {
                return Strings.Substring(0, Strings.Length - Str.Length);
            }
            return Strings;
        }
        #endregion

        public static string InputTexts(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            text = Regex.Replace(text, @"[\s]{2,}", " ");
            text = Regex.Replace(text, @"(<[b|B][r|R]/*>)+|(<[p|P](.|\n)*?>)", "\n");
            text = Regex.Replace(text, @"(\s*&[n|N][b|B][s|S][p|P];\s*)+", " ");
            text = Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
            text = text.Replace("'", "''");
            return text;
        }

        public static string SubStringAndAppend(string str, int length, string appendCode)
        {
            return (subString(str, length) + ((str.Length > length) ? appendCode : ""));
        }

        public static string subString(string SoucreStr, int len)
        {
            string str = SoucreStr;
            if (SoucreStr.Length >= len)
            {
                str = SoucreStr.Substring(0, len);
            }
            return str;
        }

        public static string subString(string str, int begin, int length)
        {
            if (str.Length < begin)
            {
                return "";
            }
            if (length >= (str.Length - begin))
            {
                length = str.Length - begin;
            }
            return str.Substring(begin, length);
        }

        #region Chr转换
        /// <summary>
        /// Chr转换
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static char CHR(int i)
        {
            char ch = (char)i;
            return ch;
        }
        #endregion

        #region 从HTML中获取文本,保留br,p,img
        /// <summary>
        /// 从HTML中获取文本,保留br,p,img
        /// </summary>
        /// <param name="HTML"></param>
        /// <returns></returns>
        public static string GetTextFromHTML(string HTML)
        {
            System.Text.RegularExpressions.Regex regEx = new System.Text.RegularExpressions.Regex(@"</?(?!br|/?p|img)[^>]*>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            return regEx.Replace(HTML, "");
        }

        public static bool IsRuleTip(Hashtable NewHash, string ruletype, out string key)
        {
            key = "";
            foreach (DictionaryEntry str in NewHash)
            {

                try
                {
                    string[] single = str.Value.ToString().SplitString("\r\n");

                    foreach (string strs in single)
                    {
                        if (strs != "")


                            switch (ruletype.Trim().ToLower())
                            {
                                case "email":
                                    if (PageValidator.IsEmail(strs.ToString()) == false)
                                        throw new Exception();
                                    break;

                                case "ip":
                                    if (PageValidator.IsIPAddress(strs.ToString()) == false)
                                        throw new Exception();
                                    break;

                                case "timesect":
                                    string[] splitetime = strs.Split('-');
                                    if (PageValidator.IsTime(splitetime[1].ToString()) == false || PageValidator.IsTime(splitetime[0].ToString()) == false)
                                        throw new Exception();
                                    break;
                            }
                    }
                }
                catch
                {
                    key = str.Key.ToString();
                    return false;
                }
            }
            return true;
        }
        #endregion


        #region 根据头、尾来截断字符串内容

        /// <summary>
        /// 先将一些特殊东西替换
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string enReplaceStr(string str)
        {
            if ((str == null) || (str == ""))
            {
                return "stringgggg_空值";
            }
            return str.Replace("\r", "stringgggg_回车").Replace("\n", "stringgggg_换行").Replace("\"", "stringgggg_双引").Replace("\\", "stringgggg_反斜");
        }

        /// <summary>
        /// 最后还原那些特殊的东西
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string deReplaceStr(string str)
        {
            return str.Replace("stringgggg_回车", "\r").Replace("stringgggg_换行", "\n").Replace("stringgggg_双引", "\"").Replace("stringgggg_反斜", "\\").Replace("stringgggg_空值", "").Replace("stringgggg_空头", "").Replace("stringgggg_空尾", "");
        }

        private static string GetRegexResult(Regex re, string sign, string matchStr)
        {
            Match match = re.Match(matchStr);
            return re.Replace(match.ToString(), sign);
        }

        private static string JSStr()
        {
            //return "function Main(s1,s2,s3)\r\n{\r\n\tvar s = GetRegex(s1, s2);\r\n      return MatchString(s,s3);\r\n}\r\n\r\nfunction GetRegex(str1, str2, group)\r\n\t\t\t{\r\n\t\t\t\tif (str1.length==0 || str2.length==0){\r\n\t\t\t\t\treturn '';\r\n\t\t\t\t}\r\n\t\t\t\tvar exs = new Array(/\\\\/gi, /\\^/gi, /\\$/gi, /\\{/gi, /\\[/gi, /\\./gi, /\\(/gi,/\\)/gi, /\\*/gi, /\\+/gi, /\\?/gi, /\\!/gi, /\\#/gi,/\\|/gi);\r\n\t\t\t\tvar chars = new Array('\\\\', '^', '$', '{', '[', '.', '(',')', '*', '+', '?', '!', '#', '|');\r\n\t\t\t\tfor(i=0; i<exs.length; i++){\r\n\t\t\t\t\tstr1 = str1.replace(exs[i],'\\\\'+chars[i]);\r\n\t\t\t\t\tstr2 = str2.replace(exs[i],'\\\\'+chars[i]);\r\n\t\t\t\t}\r\n\t\t\t\tif (group==null){\r\n\t\t\t\t\tstr1 = str1.replace(/\\r/ig,'\\\\s').replace(/\\n/ig,'\\\\s');\r\n\t\t\t\t\tstr2 = str2.replace(/\\r/ig,'\\\\s').replace(/\\n/ig,'\\\\s');\r\n\t\t\t\t\treturn str1 +'((.|\\\\n)+?)'+ str2\r\n\t\t\t\t}else{\r\n\t\t\t\t\treturn str1 +'(?<'+group+'>.+?)'+ str2\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\nfunction MatchString(s,d)\r\n\t\t\t{\r\n\t\t\t\tvar re, arr;\r\n\t\t\t\teval('re=/'+ s.replace(/\\//g,'\\\\/') +'/igm;');\r\n\t\t\t\tarr = re.exec(d);\r\n\t\t\t\tif (arr!=null){\r\n\t\t\t\t\ts = '';\r\n\t\t\t\t\t\ts += arr[1];\r\n\t\t\t\t\treturn s;\r\n\t\t\t\t}else{\r\n\t\t\t\t\treturn ('没匹配的内容');\r\n\t\t\t\t}\r\n\t\t\t}";
            return "function Main(s1,s2,s3){var s = GetRegex(s1, s2);var Result = MatchString(s,s3);if(Result.length<2 || Result.indexOf(s1)<1){return Result;}else{return Main(s1,s2,Result+s2);}}\r\nfunction GetRegex(str1, str2, group)\r\n\t\t\t{\r\n\t\t\t\tif (str1.length==0 || str2.length==0){\r\n\t\t\t\t\treturn '';\r\n\t\t\t\t}\r\n\t\t\t\tvar exs = new Array(/\\\\/gi, /\\^/gi, /\\$/gi, /\\{/gi, /\\[/gi, /\\./gi, /\\(/gi,/\\)/gi, /\\*/gi, /\\+/gi, /\\?/gi, /\\!/gi, /\\#/gi,/\\|/gi);\r\n\t\t\t\tvar chars = new Array('\\\\', '^', '$', '{', '[', '.', '(',')', '*', '+', '?', '!', '#', '|');\r\n\t\t\t\tfor(i=0; i<exs.length; i++){\r\n\t\t\t\t\tstr1 = str1.replace(exs[i],'\\\\'+chars[i]);\r\n\t\t\t\t\tstr2 = str2.replace(exs[i],'\\\\'+chars[i]);\r\n\t\t\t\t}\r\n\t\t\t\tif (group==null){\r\n\t\t\t\t\tstr1 = str1.replace(/\\r/ig,'\\\\s').replace(/\\n/ig,'\\\\s');\r\n\t\t\t\t\tstr2 = str2.replace(/\\r/ig,'\\\\s').replace(/\\n/ig,'\\\\s');\r\n\t\t\t\t\treturn str1 +'((.|\\\\n)+?)'+ str2\r\n\t\t\t\t}else{\r\n\t\t\t\t\treturn str1 +'(?<'+group+'>.+?)'+ str2\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\nfunction MatchString(s,d)\r\n\t\t\t{\r\n\t\t\t\tvar re, arr;\r\n\t\t\t\teval('re=/'+ s.replace(/\\//g,'\\\\/') +'/igm;');\r\n\t\t\t\tarr = re.exec(d);\r\n\t\t\t\tif (arr!=null){\r\n\t\t\t\t\ts = '';\r\n\t\t\t\t\t\ts += arr[1];\r\n\t\t\t\t\treturn s;\r\n\t\t\t\t}else{\r\n\t\t\t\t\treturn ('');\r\n\t\t\t\t}\r\n\t\t\t}";//2011-03-07
        }
        #endregion

        #region 替换格式为文本
        /// <summary>
        /// 替换格式为文本
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string TOTXT(this string str)
        {
            return str.Replace("\r\n", "").Replace(" ", "");
        }
        #endregion

        #region 繁简互转
        /// <summary>
        /// 繁简互转
        /// </summary>
        /// <param name="content">要处理的内容</param>
        /// <param name="isToSimple">true:转为简体 false:转为繁体</param>
        /// <returns>要处理的内容</returns>
        public static string Trans(string content, bool isToSimple)
        {
            //注意：简体有些字没有，仍用繁体字。如下：“琺”
            //新加的字都放在前面
            string complex = "槓穌靨嘆繽軼隻製嚀幺皚藹礙愛翺襖奧壩罷擺敗頒辦絆幫綁鎊謗剝飽寶報鮑輩貝鋇狽備憊繃筆畢斃幣閉邊編貶變辯辮標鼈別癟瀕濱賓擯餅並撥缽鉑駁蔔補財參蠶殘慚慘燦蒼艙倉滄廁側冊測層詫攙摻蟬饞讒纏鏟産闡顫場嘗長償腸廠暢鈔車徹塵沈陳襯撐稱懲誠騁癡遲馳恥齒熾沖蟲寵疇躊籌綢醜櫥廚鋤雛礎儲觸處傳瘡闖創錘純綽辭詞賜聰蔥囪從叢湊躥竄錯達帶貸擔單鄲撣膽憚誕彈當擋黨蕩檔搗島禱導盜燈鄧敵滌遞締顛點墊電澱釣調叠諜疊釘頂錠訂丟東動棟凍鬥犢獨讀賭鍍鍛斷緞兌隊對噸頓鈍奪墮鵝額訛惡餓兒爾餌貳發罰閥琺礬釩煩範販飯訪紡飛誹廢費紛墳奮憤糞豐楓鋒風瘋馮縫諷鳳膚輻撫輔賦複負訃婦縛該鈣蓋幹趕稈贛岡剛鋼綱崗臯鎬擱鴿閣鉻個給龔宮鞏貢鈎溝構購夠蠱顧剮關觀館慣貫廣規矽歸龜閨軌詭櫃貴劊輥滾鍋國過駭韓漢號閡鶴賀橫轟鴻紅後壺護滬戶嘩華畫劃話懷壞歡環還緩換喚瘓煥渙黃謊揮輝毀賄穢會燴彙諱誨繪葷渾夥獲貨禍擊機積饑譏雞績緝極輯級擠幾薊劑濟計記際繼紀夾莢頰賈鉀價駕殲監堅箋間艱緘繭檢堿鹼揀撿簡儉減薦檻鑒踐賤見鍵艦劍餞漸濺澗將漿蔣槳獎講醬膠澆驕嬌攪鉸矯僥腳餃繳絞轎較稭階節莖鯨驚經頸靜鏡徑痙競淨糾廄舊駒舉據鋸懼劇鵑絹傑潔結誡屆緊錦僅謹進晉燼盡勁荊覺決訣絕鈞軍駿開凱顆殼課墾懇摳庫褲誇塊儈寬礦曠況虧巋窺饋潰擴闊蠟臘萊來賴藍欄攔籃闌蘭瀾讕攬覽懶纜爛濫撈勞澇樂鐳壘類淚籬離裏鯉禮麗厲勵礫曆瀝隸倆聯蓮連鐮憐漣簾斂臉鏈戀煉練糧涼兩輛諒療遼鐐獵臨鄰鱗凜賃齡鈴淩靈嶺領餾劉龍聾嚨籠壟攏隴樓婁摟簍蘆盧顱廬爐擄鹵虜魯賂祿錄陸驢呂鋁侶屢縷慮濾綠巒攣孿灤亂掄輪倫侖淪綸論蘿羅邏鑼籮騾駱絡媽瑪碼螞馬罵嗎買麥賣邁脈瞞饅蠻滿謾貓錨鉚貿麽黴沒鎂門悶們錳夢謎彌覓冪綿緬廟滅憫閩鳴銘謬謀畝鈉納難撓腦惱鬧餒內擬膩攆撚釀鳥聶齧鑷鎳檸獰甯擰濘鈕紐膿濃農瘧諾歐鷗毆嘔漚盤龐賠噴鵬騙飄頻貧蘋憑評潑頗撲鋪樸譜棲淒臍齊騎豈啓氣棄訖牽扡釺鉛遷簽謙錢鉗潛淺譴塹槍嗆牆薔強搶鍬橋喬僑翹竅竊欽親寢輕氫傾頃請慶瓊窮趨區軀驅齲顴權勸卻鵲確讓饒擾繞熱韌認紉榮絨軟銳閏潤灑薩鰓賽叁傘喪騷掃澀殺紗篩曬刪閃陝贍繕傷賞燒紹賒攝懾設紳審嬸腎滲聲繩勝聖師獅濕詩屍時蝕實識駛勢適釋飾視試壽獸樞輸書贖屬術樹豎數帥雙誰稅順說碩爍絲飼聳慫頌訟誦擻蘇訴肅雖隨綏歲孫損筍縮瑣鎖獺撻擡態攤貪癱灘壇譚談歎湯燙濤縧討騰謄銻題體屜條貼鐵廳聽烴銅統頭禿圖塗團頹蛻脫鴕馱駝橢窪襪彎灣頑萬網韋違圍爲濰維葦偉僞緯謂衛溫聞紋穩問甕撾蝸渦窩臥嗚鎢烏汙誣無蕪吳塢霧務誤錫犧襲習銑戲細蝦轄峽俠狹廈嚇鍁鮮纖鹹賢銜閑顯險現獻縣餡羨憲線廂鑲鄉詳響項蕭囂銷曉嘯蠍協挾攜脅諧寫瀉謝鋅釁興洶鏽繡虛噓須許敘緒續軒懸選癬絢學勳詢尋馴訓訊遜壓鴉鴨啞亞訝閹煙鹽嚴顔閻豔厭硯彥諺驗鴦楊揚瘍陽癢養樣瑤搖堯遙窯謠藥爺頁業葉醫銥頤遺儀彜蟻藝億憶義詣議誼譯異繹蔭陰銀飲隱櫻嬰鷹應纓瑩螢營熒蠅贏穎喲擁傭癰踴詠湧優憂郵鈾猶遊誘輿魚漁娛與嶼語籲禦獄譽預馭鴛淵轅園員圓緣遠願約躍鑰嶽粵悅閱雲鄖勻隕運蘊醞暈韻雜災載攢暫贊贓髒鑿棗竈責擇則澤賊贈紮劄軋鍘閘柵詐齋債氈盞斬輾嶄棧戰綻張漲帳賬脹趙蟄轍鍺這貞針偵診鎮陣掙睜猙爭幀鄭證織職執紙摯擲幟質滯鍾終種腫衆謅軸皺晝驟豬諸誅燭矚囑貯鑄築駐專磚轉賺樁莊裝妝壯狀錐贅墜綴諄著濁茲資漬蹤綜總縱鄒詛組鑽為麼於產崙眾餘衝準兇佔歷釐髮臺嚮啟週譁薑寧傢尷鉅乾倖徵逕誌愴恆託摺掛闆樺慾洩瀏薰箏籤蹧係紓燿骼臟捨甦盪穫讚輒蹟跡採裡鐘鏢閒闕僱靂獃騃佈牀脣閧鬨崑崐綑蔴阩昇牠蓆巖灾剳紥註";
            string simple = "杠稣厣叹缤轶只制咛么皑蔼碍爱翱袄奥坝罢摆败颁办绊帮绑镑谤剥饱宝报鲍辈贝钡狈备惫绷笔毕毙币闭边编贬变辩辫标鳖别瘪濒滨宾摈饼并拨钵铂驳卜补财参蚕残惭惨灿苍舱仓沧厕侧册测层诧搀掺蝉馋谗缠铲产阐颤场尝长偿肠厂畅钞车彻尘沉陈衬撑称惩诚骋痴迟驰耻齿炽冲虫宠畴踌筹绸丑橱厨锄雏础储触处传疮闯创锤纯绰辞词赐聪葱囱从丛凑蹿窜错达带贷担单郸掸胆惮诞弹当挡党荡档捣岛祷导盗灯邓敌涤递缔颠点垫电淀钓调迭谍叠钉顶锭订丢东动栋冻斗犊独读赌镀锻断缎兑队对吨顿钝夺堕鹅额讹恶饿儿尔饵贰发罚阀琺矾钒烦范贩饭访纺飞诽废费纷坟奋愤粪丰枫锋风疯冯缝讽凤肤辐抚辅赋复负讣妇缚该钙盖干赶秆赣冈刚钢纲岗皋镐搁鸽阁铬个给龚宫巩贡钩沟构购够蛊顾剐关观馆惯贯广规硅归龟闺轨诡柜贵刽辊滚锅国过骇韩汉号阂鹤贺横轰鸿红后壶护沪户哗华画划话怀坏欢环还缓换唤痪焕涣黄谎挥辉毁贿秽会烩汇讳诲绘荤浑伙获货祸击机积饥讥鸡绩缉极辑级挤几蓟剂济计记际继纪夹荚颊贾钾价驾歼监坚笺间艰缄茧检碱硷拣捡简俭减荐槛鉴践贱见键舰剑饯渐溅涧将浆蒋桨奖讲酱胶浇骄娇搅铰矫侥脚饺缴绞轿较秸阶节茎鲸惊经颈静镜径痉竞净纠厩旧驹举据锯惧剧鹃绢杰洁结诫届紧锦仅谨进晋烬尽劲荆觉决诀绝钧军骏开凯颗壳课垦恳抠库裤夸块侩宽矿旷况亏岿窥馈溃扩阔蜡腊莱来赖蓝栏拦篮阑兰澜谰揽览懒缆烂滥捞劳涝乐镭垒类泪篱离里鲤礼丽厉励砾历沥隶俩联莲连镰怜涟帘敛脸链恋炼练粮凉两辆谅疗辽镣猎临邻鳞凛赁龄铃凌灵岭领馏刘龙聋咙笼垄拢陇楼娄搂篓芦卢颅庐炉掳卤虏鲁赂禄录陆驴吕铝侣屡缕虑滤绿峦挛孪滦乱抡轮伦仑沦纶论萝罗逻锣箩骡骆络妈玛码蚂马骂吗买麦卖迈脉瞒馒蛮满谩猫锚铆贸么霉没镁门闷们锰梦谜弥觅幂绵缅庙灭悯闽鸣铭谬谋亩钠纳难挠脑恼闹馁内拟腻撵捻酿鸟聂啮镊镍柠狞宁拧泞钮纽脓浓农疟诺欧鸥殴呕沤盘庞赔喷鹏骗飘频贫苹凭评泼颇扑铺朴谱栖凄脐齐骑岂启气弃讫牵扦钎铅迁签谦钱钳潜浅谴堑枪呛墙蔷强抢锹桥乔侨翘窍窃钦亲寝轻氢倾顷请庆琼穷趋区躯驱龋颧权劝却鹊确让饶扰绕热韧认纫荣绒软锐闰润洒萨鳃赛三伞丧骚扫涩杀纱筛晒删闪陕赡缮伤赏烧绍赊摄慑设绅审婶肾渗声绳胜圣师狮湿诗尸时蚀实识驶势适释饰视试寿兽枢输书赎属术树竖数帅双谁税顺说硕烁丝饲耸怂颂讼诵擞苏诉肃虽随绥岁孙损笋缩琐锁獭挞抬态摊贪瘫滩坛谭谈叹汤烫涛绦讨腾誊锑题体屉条贴铁厅听烃铜统头秃图涂团颓蜕脱鸵驮驼椭洼袜弯湾顽万网韦违围为潍维苇伟伪纬谓卫温闻纹稳问瓮挝蜗涡窝卧呜钨乌污诬无芜吴坞雾务误锡牺袭习铣戏细虾辖峡侠狭厦吓锨鲜纤咸贤衔闲显险现献县馅羡宪线厢镶乡详响项萧嚣销晓啸蝎协挟携胁谐写泻谢锌衅兴汹锈绣虚嘘须许叙绪续轩悬选癣绚学勋询寻驯训讯逊压鸦鸭哑亚讶阉烟盐严颜阎艳厌砚彦谚验鸯杨扬疡阳痒养样瑶摇尧遥窑谣药爷页业叶医铱颐遗仪彝蚁艺亿忆义诣议谊译异绎荫阴银饮隐樱婴鹰应缨莹萤营荧蝇赢颖哟拥佣痈踊咏涌优忧邮铀犹游诱舆鱼渔娱与屿语吁御狱誉预驭鸳渊辕园员圆缘远愿约跃钥岳粤悦阅云郧匀陨运蕴酝晕韵杂灾载攒暂赞赃脏凿枣灶责择则泽贼赠扎札轧铡闸栅诈斋债毡盏斩辗崭栈战绽张涨帐账胀赵蛰辙锗这贞针侦诊镇阵挣睁狰争帧郑证织职执纸挚掷帜质滞钟终种肿众诌轴皱昼骤猪诸诛烛瞩嘱贮铸筑驻专砖转赚桩庄装妆壮状锥赘坠缀谆着浊兹资渍踪综总纵邹诅组钻为么于产仑众余冲准凶占历厘发台向启周哗姜宁家尴巨干幸征径志怆恒托折挂板桦欲泄浏熏筝签糟系纾耀胳脏舍苏荡获赞辄迹迹采里钟镖闲阙雇雳呆呆布床唇哄哄昆昆捆麻升升它席岩灾札扎注";
            string str = "";
            if (isToSimple)
            {
                for (int i = 0; i < content.Length; i++)
                {
                    string word = content.Substring(i, 1);
                    //忽略字母
                    if (string.CompareOrdinal(word, "~") <= 0)
                    {
                        str += word;
                        continue;
                    }
                    int pos = complex.IndexOf(word);
                    if (pos != -1)
                        str += simple.Substring(pos, 1);
                    else
                        str += word;
                }
            }
            else
            {
                for (int i = 0; i < content.Length; i++)
                {
                    string word = content.Substring(i, 1);
                    //忽略字母
                    if (string.CompareOrdinal(word, "~") <= 0)
                    {
                        str += word;
                        continue;
                    }
                    int pos = simple.IndexOf(word);
                    if (pos != -1)
                        str += complex.Substring(pos, 1);
                    else
                        str += word;
                }
            }
            return str;
        }

        /// <summary>
        /// 转换为简体中文
        /// </summary>
        public static string ToSChinese(string str)
        {
            return Microsoft.VisualBasic.Strings.StrConv(str, Microsoft.VisualBasic.VbStrConv.SimplifiedChinese, 0);
        }

        /// <summary>
        /// 转换为繁体中文
        /// </summary>
        public static string ToTChinese(string str)
        {
            return Microsoft.VisualBasic.Strings.StrConv(str, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, 0);
        }

        #region 将繁体中文转化成简体中文
        /// <summary>
        /// 将繁体中文转化成简体中文
        /// </summary>
        /// <param name="str">繁体中文字符串</param>
        /// <returns></returns>
        public static string ConvertToSimplifiedChinese(string str)
        {
            return Microsoft.VisualBasic.Strings.StrConv(str, Microsoft.VisualBasic.VbStrConv.SimplifiedChinese, CultureInfo.CurrentUICulture.LCID);
        }
        #endregion

        #region 将简体中文转化成繁体中文
        /// <summary>
        /// 将简体中文转化成繁体中文
        /// </summary>
        /// <param name="str">简体中文字符串</param>
        /// <returns></returns>
        public static string ConvertToTraditionalChinese(string str)
        {
            return Microsoft.VisualBasic.Strings.StrConv(str, Microsoft.VisualBasic.VbStrConv.TraditionalChinese, CultureInfo.CurrentUICulture.LCID);
        }
        #endregion
        #endregion

        #region 将指定字符串中的汉字转换为拼音首字母的缩写，其中非汉字保留为原字符
        /// <summary>
        /// 将指定字符串中的汉字转换为拼音首字母的缩写，其中非汉字保留为原字符
        /// </summary>
        /// <param name="text">要转换的文本内容</param>
        /// <returns></returns>
        public static string ConvertSpellFirst(string text)
        {
            StringBuilder builder = new StringBuilder(text.Length);
            foreach (char ch2 in text)
            {
                char ch = ch2;
                byte[] bytes = Encoding.Default.GetBytes(new char[] { ch2 });
                if (bytes.Length == 2)
                {
                    int num = (bytes[0] * 0x100) + bytes[1];
                    if (num < 0xb0a1)
                    {
                        ch = ch2;
                    }
                    else if (num < 0xb0c5)
                    {
                        ch = 'a';
                    }
                    else if (num < 0xb2c1)
                    {
                        ch = 'b';
                    }
                    else if (num < 0xb4ee)
                    {
                        ch = 'c';
                    }
                    else if (num < 0xb6ea)
                    {
                        ch = 'd';
                    }
                    else if (num < 0xb7a2)
                    {
                        ch = 'e';
                    }
                    else if (num < 0xb8c1)
                    {
                        ch = 'f';
                    }
                    else if (num < 0xb9fe)
                    {
                        ch = 'g';
                    }
                    else if (num < 0xbbf7)
                    {
                        ch = 'h';
                    }
                    else if (num < 0xbfa6)
                    {
                        ch = 'g';
                    }
                    else if (num < 0xc0ac)
                    {
                        ch = 'k';
                    }
                    else if (num < 0xc2e8)
                    {
                        ch = 'l';
                    }
                    else if (num < 0xc4c3)
                    {
                        ch = 'm';
                    }
                    else if (num < 0xc5b6)
                    {
                        ch = 'n';
                    }
                    else if (num < 0xc5be)
                    {
                        ch = 'o';
                    }
                    else if (num < 0xc6da)
                    {
                        ch = 'p';
                    }
                    else if (num < 0xc8bb)
                    {
                        ch = 'q';
                    }
                    else if (num < 0xc8f6)
                    {
                        ch = 'r';
                    }
                    else if (num < 0xcbfa)
                    {
                        ch = 's';
                    }
                    else if (num < 0xcdda)
                    {
                        ch = 't';
                    }
                    else if (num < 0xcef4)
                    {
                        ch = 'w';
                    }
                    else if (num < 0xd1b9)
                    {
                        ch = 'x';
                    }
                    else if (num < 0xd4d1)
                    {
                        ch = 'y';
                    }
                    else if (num < 0xd7fa)
                    {
                        ch = 'z';
                    }
                }
                builder.Append(ch);
            }
            return builder.ToString();
        }
        #endregion

        #region 将指定字符串中的汉字转换为拼音字母，其中非汉字保留为原字符
        /// <summary>
        /// 将指定字符串中的汉字转换为拼音字母，其中非汉字保留为原字符
        /// </summary>
        /// <param name="text">要转换的文本内容</param>
        /// <returns></returns>
        public static string ConvertSpellFull(string text)
        {
            int[] numArray = new int[] { 
        -20319, -20317, -20304, -20295, -20292, -20283, -20265, -20257, -20242, -20230, -20051, -20036, -20032, -20026, -20002, -19990, 
        -19986, -19982, -19976, -19805, -19784, -19775, -19774, -19763, -19756, -19751, -19746, -19741, -19739, -19728, -19725, -19715, 
        -19540, -19531, -19525, -19515, -19500, -19484, -19479, -19467, -19289, -19288, -19281, -19275, -19270, -19263, -19261, -19249, 
        -19243, -19242, -19238, -19235, -19227, -19224, -19218, -19212, -19038, -19023, -19018, -19006, -19003, -18996, -18977, -18961, 
        -18952, -18783, -18774, -18773, -18763, -18756, -18741, -18735, -18731, -18722, -18710, -18697, -18696, -18526, -18518, -18501, 
        -18490, -18478, -18463, -18448, -18447, -18446, -18239, -18237, -18231, -18220, -18211, -18201, -18184, -18183, -18181, -18012, 
        -17997, -17988, -17970, -17964, -17961, -17950, -17947, -17931, -17928, -17922, -17759, -17752, -17733, -17730, -17721, -17703, 
        -17701, -17697, -17692, -17683, -17676, -17496, -17487, -17482, -17468, -17454, -17433, -17427, -17417, -17202, -17185, -16983, 
        -16970, -16942, -16915, -16733, -16708, -16706, -16689, -16664, -16657, -16647, -16474, -16470, -16465, -16459, -16452, -16448, 
        -16433, -16429, -16427, -16423, -16419, -16412, -16407, -16403, -16401, -16393, -16220, -16216, -16212, -16205, -16202, -16187, 
        -16180, -16171, -16169, -16158, -16155, -15959, -15958, -15944, -15933, -15920, -15915, -15903, -15889, -15878, -15707, -15701, 
        -15681, -15667, -15661, -15659, -15652, -15640, -15631, -15625, -15454, -15448, -15436, -15435, -15419, -15416, -15408, -15394, 
        -15385, -15377, -15375, -15369, -15363, -15362, -15183, -15180, -15165, -15158, -15153, -15150, -15149, -15144, -15143, -15141, 
        -15140, -15139, -15128, -15121, -15119, -15117, -15110, -15109, -14941, -14937, -14933, -14930, -14929, -14928, -14926, -14922, 
        -14921, -14914, -14908, -14902, -14894, -14889, -14882, -14873, -14871, -14857, -14678, -14674, -14670, -14668, -14663, -14654, 
        -14645, -14630, -14594, -14429, -14407, -14399, -14384, -14379, -14368, -14355, -14353, -14345, -14170, -14159, -14151, -14149, 
        -14145, -14140, -14137, -14135, -14125, -14123, -14122, -14112, -14109, -14099, -14097, -14094, -14092, -14090, -14087, -14083, 
        -13917, -13914, -13910, -13907, -13906, -13905, -13896, -13894, -13878, -13870, -13859, -13847, -13831, -13658, -13611, -13601, 
        -13406, -13404, -13400, -13398, -13395, -13391, -13387, -13383, -13367, -13359, -13356, -13343, -13340, -13329, -13326, -13318, 
        -13147, -13138, -13120, -13107, -13096, -13095, -13091, -13076, -13068, -13063, -13060, -12888, -12875, -12871, -12860, -12858, 
        -12852, -12849, -12838, -12831, -12829, -12812, -12802, -12607, -12597, -12594, -12585, -12556, -12359, -12346, -12320, -12300, 
        -12120, -12099, -12089, -12074, -12067, -12058, -12039, -11867, -11861, -11847, -11831, -11798, -11781, -11604, -11589, -11536, 
        -11358, -11340, -11339, -11324, -11303, -11097, -11077, -11067, -11055, -11052, -11045, -11041, -11038, -11024, -11020, -11019, 
        -11018, -11014, -10838, -10832, -10815, -10800, -10790, -10780, -10764, -10587, -10544, -10533, -10519, -10331, -10329, -10328, 
        -10322, -10315, -10309, -10307, -10296, -10281, -10274, -10270, -10262, -10260, -10256, -10254
     };
            string[] strArray = new string[] { 
        "a", "ai", "an", "ang", "ao", "ba", "bai", "ban", "bang", "bao", "bei", "ben", "beng", "bi", "bian", "biao", 
        "bie", "bin", "bing", "bo", "bu", "ca", "cai", "can", "cang", "cao", "ce", "ceng", "cha", "chai", "chan", "chang", 
        "chao", "che", "chen", "cheng", "chi", "chong", "chou", "chu", "chuai", "chuan", "chuang", "chui", "chun", "chuo", "ci", "cong", 
        "cou", "cu", "cuan", "cui", "cun", "cuo", "da", "dai", "dan", "dang", "dao", "de", "deng", "di", "dian", "diao", 
        "die", "ding", "diu", "dong", "dou", "du", "duan", "dui", "dun", "duo", "e", "en", "er", "fa", "fan", "fang", 
        "fei", "fen", "feng", "fo", "fou", "fu", "ga", "gai", "gan", "gang", "gao", "ge", "gei", "gen", "geng", "gong", 
        "gou", "gu", "gua", "guai", "guan", "guang", "gui", "gun", "guo", "ha", "hai", "han", "hang", "hao", "he", "hei", 
        "hen", "heng", "hong", "hou", "hu", "hua", "huai", "huan", "huang", "hui", "hun", "huo", "ji", "jia", "jian", "jiang", 
        "jiao", "jie", "jin", "jing", "jiong", "jiu", "ju", "juan", "jue", "jun", "ka", "kai", "kan", "kang", "kao", "ke", 
        "ken", "keng", "kong", "kou", "ku", "kua", "kuai", "kuan", "kuang", "kui", "kun", "kuo", "la", "lai", "lan", "lang", 
        "lao", "le", "lei", "leng", "li", "lia", "lian", "liang", "liao", "lie", "lin", "ling", "liu", "long", "lou", "lu", 
        "lv", "luan", "lue", "lun", "luo", "ma", "mai", "man", "mang", "mao", "me", "mei", "men", "meng", "mi", "mian", 
        "miao", "mie", "min", "ming", "miu", "mo", "mou", "mu", "na", "nai", "nan", "nang", "nao", "ne", "nei", "nen", 
        "neng", "ni", "nian", "niang", "niao", "nie", "nin", "ning", "niu", "nong", "nu", "nv", "nuan", "nue", "nuo", "o", 
        "ou", "pa", "pai", "pan", "pang", "pao", "pei", "pen", "peng", "pi", "pian", "piao", "pie", "pin", "ping", "po", 
        "pu", "qi", "qia", "qian", "qiang", "qiao", "qie", "qin", "qing", "qiong", "qiu", "qu", "quan", "que", "qun", "ran", 
        "rang", "rao", "re", "ren", "reng", "ri", "rong", "rou", "ru", "ruan", "rui", "run", "ruo", "sa", "sai", "san", 
        "sang", "sao", "se", "sen", "seng", "sha", "shai", "shan", "shang", "shao", "she", "shen", "sheng", "shi", "shou", "shu", 
        "shua", "shuai", "shuan", "shuang", "shui", "shun", "shuo", "si", "song", "sou", "su", "suan", "sui", "sun", "suo", "ta", 
        "tai", "tan", "tang", "tao", "te", "teng", "ti", "tian", "tiao", "tie", "ting", "tong", "tou", "tu", "tuan", "tui", 
        "tun", "tuo", "wa", "wai", "wan", "wang", "wei", "wen", "weng", "wo", "wu", "xi", "xia", "xian", "xiang", "xiao", 
        "xie", "xin", "xing", "xiong", "xiu", "xu", "xuan", "xue", "xun", "ya", "yan", "yang", "yao", "ye", "yi", "yin", 
        "ying", "yo", "yong", "you", "yu", "yuan", "yue", "yun", "za", "zai", "zan", "zang", "zao", "ze", "zei", "zen", 
        "zeng", "zha", "zhai", "zhan", "zhang", "zhao", "zhe", "zhen", "zheng", "zhi", "zhong", "zhou", "zhu", "zhua", "zhuai", "zhuan", 
        "zhuang", "zhui", "zhun", "zhuo", "zi", "zong", "zou", "zu", "zuan", "zui", "zun", "zuo"
     };
            byte[] bytes = new byte[2];
            string str = "";
            int num = 0;
            int num2 = 0;
            int num3 = 0;
            char[] chArray = text.ToCharArray();
            for (int i = 0; i < chArray.Length; i++)
            {
                bytes = Encoding.Default.GetBytes(chArray[i].ToString());
                num2 = bytes[0];
                num3 = bytes[1];
                num = ((num2 * 0x100) + num3) - 0x10000;
                if ((num > 0) && (num < 160))
                {
                    str = str + chArray[i];
                }
                else
                {
                    for (int j = numArray.Length - 1; j >= 0; j--)
                    {
                        if (numArray[j] < num)
                        {
                            str = str + strArray[j];
                            break;
                        }
                    }
                }
            }
            return str;
        }
        #endregion
        /// <summary>
        /// 正则表达式取值
        /// </summary>
        /// <param name="HtmlCode">HTML代码</param>
        /// <param name="RegexString">正则表达式</param>
        /// <param name="GroupKey">正则表达式分组关键字</param>
        /// <param name="RightToLeft">是否从右到左</param>
        /// <returns></returns>
        public static string[] GetRegValue(string HtmlCode, string RegexString, string GroupKey, bool RightToLeft)
        {
            MatchCollection m;
            Regex r;
            if (RightToLeft == true)
            {
                r = new Regex(RegexString, RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.RightToLeft);
            }
            else
            {
                r = new Regex(RegexString, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            }
            m = r.Matches(HtmlCode);
            string[] MatchValue = new string[m.Count];
            for (int i = 0; i < m.Count; i++)
            {
                MatchValue[i] = m[i].Groups[GroupKey].Value;
            }
            return MatchValue;
        }

        /// <summary>
        /// 获得标签的属性值
        /// </summary>
        /// <param name="HtmlTag"></param>
        /// <param name="AttributeName"></param>
        /// <returns></returns>
        public static string AttributeValue(string HtmlTag, string AttributeName)
        {
            //前缀符号，要么为空，要么是空格/双引号/单引号/竖线/冒号……你还可以自己加入其他的符号
            string prefixCHAR = (HtmlTag.StartsWith(AttributeName + "=")) ? "(.{0})" : "([\"'\\s\\|:]{1})";
            string RegexString = prefixCHAR + AttributeName + "=(\"|')(?<" + AttributeName + ">.*?[^\\\\]{1})(\\2)";
            string[] _att = GetRegValue(HtmlTag, RegexString, AttributeName, false);
            if (_att.Length > 0)
                return _att[0].ToString();
            else
                return "";
        }

        /// <summary>        
        /// 格式化显示时间为几个月,几天前,几小时前,几分钟前,或几秒前        
        /// </summary>        
        /// <param name="dt">要格式化显示的时间</param>        
        /// <returns>几个月,几天前,几小时前,几分钟前,或几秒前</returns>        
        public static string DateStringFromNow(DateTime dt)
        {
            TimeSpan span = DateTime.Now - dt;
            if (span.TotalDays > 60) { return dt.ToShortDateString(); }
            else if (span.TotalDays > 30) { return "1个月前"; }
            else if (span.TotalDays > 14) { return "2周前"; }
            else if (span.TotalDays > 7) { return "1周前"; }
            else if (span.TotalDays > 1) { return string.Format("{0}天前", (int)Math.Floor(span.TotalDays)); }
            else if (span.TotalHours > 1) { return string.Format("{0}小时前", (int)Math.Floor(span.TotalHours)); }
            else if (span.TotalMinutes > 1) { return string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes)); }
            else if (span.TotalSeconds >= 1) { return string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds)); }
            else { return "1秒前"; }
        }

    }
}
